package main;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;



public class filedownload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //上传的文件都是保存在/WEB-INF/file目录下的子目录当中
        String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/AppFile");


        //String fileName =  this.getFileName(request.getRequestURI());
        String fileName = request.getParameter("fileName");

        if (fileName == null){
            fileName =  this.getFileName(request.getRequestURI());
        }
        System.out.println("download fileName : " + fileName);
        //通过文件名找出文件的所在目录
        String fileFullPath =  fileSaveRootPath +  "/" + fileName;


        String fileNameUTF8 =  URLEncoder.encode(fileName, "UTF-8");


        //设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + fileNameUTF8);
        //response.setHeader("content-type", "application/vnd.android.package-archive");
        response.setHeader("Content-Type", "application/octet-stream");

        response.setContentType("application/octet-stream");//说明浏览器这是二进制输出流
        try{

            //读取要下载的文件，保存到文件输入流
            FileInputStream in = new FileInputStream(fileFullPath);
            //创建输出流
            OutputStream out = response.getOutputStream();
            //创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while((len=in.read(buffer))>0){
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
            //关闭文件输入流
            in.close();
            //关闭输出流
            out.close();



        }catch (Exception e){

            System.out.println(e.getMessage());

            PrintWriter pw = response.getWriter();
            pw.write("下载错误");
            pw.close();
        }



    }
    private    String getFileName(String path){
        String fName = path.trim();
        String fileName = fName.substring(fName.lastIndexOf("/")+1);
        return fileName;
    }

}
